//package com.douqu.game.auth.web.controller;
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.alipay.api.AlipayApiException;
//import com.alipay.api.internal.util.AlipaySignature;
//import com.bean.core.pay.alipay.AlipayConfig;
//import com.bean.core.pay.tenpay.bean.TenpayTradeNotifyInfo;
//import com.bean.core.pay.tenpay.bean.TenpayTradeReceiptInfo;
//import com.bean.core.util.HttpJsonUtils;
//import com.bean.core.util.MD5Utils;
//import com.bean.core.util.TimeUtils;
//import com.bean.core.util.Utils;
//import com.douqu.game.auth.database.mapper.ServerMapper;
//import com.douqu.game.auth.database.model.ServerModel;
//import com.douqu.game.auth.server.WorldManager;
//import com.douqu.game.auth.service.OrderRecordService;
//import com.douqu.game.auth.service.PlayerService;
//import com.douqu.game.auth.web.request.AliCheckOrderReqParam;
//import com.douqu.game.auth.web.request.PPCheckOrderReqParam;
//import com.douqu.game.auth.web.request.YjCheckOrderReqParam;
//import com.douqu.game.core.database.model.OrderRecordModel;
//import com.douqu.game.core.e.E_RechargeStatus;
//import com.douqu.game.core.e.ReturnMessage;
//import com.douqu.game.core.factory.ConstantFactory;
//import com.douqu.game.core.factory.HttpFactory;
//import com.douqu.game.core.factory.PlatformFactory;
//import com.douqu.game.core.protobuf.SGCommonProto;
//import com.douqu.game.core.util.ApplePayUtils;
//import com.douqu.game.core.util.LogUtils;
//import com.douqu.game.core.util.PayUtils;
//import com.douqu.game.core.web.AppStoreNotifyParam;
//import com.douqu.game.core.web.RechargeCallBackParam;
//import com.douqu.game.core.web.request.RechargeParam;
//import com.douqu.game.core.web.response.BaseResponseDto;
//import com.douqu.game.core.web.response.ErrorResponseDto;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.ServletInputStream;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.util.HashMap;
//import java.util.Map;
//
///**
//* @author wangzhenfei
//*         2018-01-17 15:42
//*         易接消费回调
//*/
//@RestController
//public class PayController111 {
//
//    @Autowired
//    PlayerService playerService;
//
//    @Autowired
//    ServerMapper serverMapper;
//
//    @Autowired
//    OrderRecordService orderRecordService;
//
//    @RequestMapping(value = "/pay/test")
//    public BaseResponseDto test(String password) throws IOException
//    {
//        LogUtils.error("收到测试数据 -> " + password);
//        LogUtils.info("request -> " + password);
//        return new BaseResponseDto(ReturnMessage.SUCCESS);
//    }
//
//    @ResponseBody
//    @RequestMapping(value = HttpFactory.PAY_INIT, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
//    public BaseResponseDto initRecharge(@RequestBody OrderRecordModel orderRecordModel)
//    {
//        orderRecordModel.setStatus(E_RechargeStatus.NO_PAY.getCode());
//        int count = orderRecordService.createOrder(orderRecordModel);
//
//        return count == 1 ? new BaseResponseDto(ReturnMessage.SUCCESS) : new ErrorResponseDto(ReturnMessage.FAILURE);
//    }
//
//    /**
//     * 易接的回调
//     *
//     * @param request
//     * @param response
//     * @throws java.io.IOException
//     */
//    @RequestMapping(value = HttpFactory.PAY_YJ_CHECK)
//    public void checkOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        PrintWriter w = response.getWriter();
//        YjCheckOrderReqParam orderReqDto = new YjCheckOrderReqParam();
//        orderReqDto.init(request);
//        LogUtils.info("回调参数：" + orderReqDto.toString());
//        if (orderReqDto.isResultOk()) {
//            // 此处CP可以持久化消费记录
//            //st==1是支付成功，才能给用户发道具
//            if (orderReqDto.isSuccess()) {
//                Integer count = orderRecordService.findCount(orderReqDto.getInnerParam().getObjectIndex(), orderReqDto.getTcd());
//                if (count == null || count == 0) { //没有成功的记录，发送奖励
//                    //TODO 发送奖励
//                    //获取服务器id
//                    Integer serverId = orderReqDto.getInnerParam().getServerId();
//                    ServerModel serverModel = serverMapper.selectByPrimaryKey(serverId);
//                    if (serverModel == null) {
//                        LogUtils.error("服务器找不到 id为:" + serverId);
//                        w.write("ERROR");
//                    } else {
//                        RechargeParam rechargeParam = orderReqDto.getInnerParam();
//                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_YJ.name());
//                        boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), serverId, rechargeParam.getObjectIndex(), orderReqDto.getCbi(),
//                                                                            rechargeParam.getOutTradeNo(), orderReqDto.getTcd(), orderReqDto.getFee(), payType, orderReqDto.getSdk());
//                        if(result)
//                        {
//                            orderRecordService.updateOrder(orderReqDto.getOrderRecordModel(payType), true);
//                            LogUtils.warn("易接冲值成功 -> " + rechargeParam.getOutTradeNo());
//                            w.write("SUCCESS");
//                        }
//                        else
//                        {
//                            LogUtils.debug("主服务器冲值回调返回错误!");
//                            w.write("ERROR");
//                        }
//
////                        String checkString = orderReqDto.getInnerParam().getServerId() + ConstantFactory.RECHARGE_KEY +
////                                TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
////                        RechargeCallBackParam param = new RechargeCallBackParam();
////                        param.setObjectIndex(orderReqDto.getInnerParam().getObjectIndex());
////                        param.setRechargeParam(orderReqDto.getCbi());
////                        param.setTcd(orderReqDto.getTcd());
////                        param.setFee(orderReqDto.getFee());
////                        param.setChannel(orderReqDto.getSdk());
////                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_YJ.name());
////                        param.setPayType(payType);
////                        param.setPassword(MD5Utils.encodeUppercase(checkString));
////
////                        LogUtils.info("参数  -> " + JSONObject.toJSONString(param));
////
////                        LogUtils.info("通知主服务器 -> " + serverModel.getMainServerRequestUrl());
////                        JSONObject result = HttpJsonUtils.httpPost(serverModel.getMainServerRequestUrl() + HttpFactory.ORDER_CHECK, param.toJSONObject());
////                        if (result != null) {
////                            String resultCode = result.getString("code");
////                            if (Integer.parseInt(resultCode) == 0)
////                            {//成功
////                                orderRecordService.updateOrder(orderReqDto.getOrderRecordModel(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_YJ.name()), true);
////                                LogUtils.info("充值成功 -> ");
////                                w.write("SUCCESS");
////                                //充值成功调用talkingData
////
////                            } else {
////                                LogUtils.error("主服务器返回充值错误：" + result.getString("message"));
////                                w.write("ERROR");
////                            }
////                        } else {
////                            LogUtils.error("主服务器返回充值错误返回为空");
////                            w.write("ERROR");
////                        }
//                    }
//
//                } else {
//                    LogUtils.error("该用户已经发放过奖励");
//                    w.write("SUCCESS");
//                }
//            }
//            // 操作成功后需要返回SUCCESS告诉易接服务器已经接收成功
//
//        } else {
//            // 返回ERROR易接服务器会根据一定的策略重新同步消费记录给CP
//            LogUtils.error("ERROR");
//            w.write("ERROR");
//        }
//        w.flush();
//        w.close();
//    }
//
//    /**
//     * 支付宝的回调
//     *
//     * @param request
//     * @param response
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = HttpFactory.PAY_NOTIFY_ALIPAY)
//    public String alipayNotify(HttpServletRequest request, HttpServletResponse response) {
//        //获取支付宝POST过来反馈信息
//        Map<String, String> params = new HashMap<String, String>();
//        Map requestParams = request.getParameterMap();
//        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
//            String name = entry.getKey();
//            String[] values = entry.getValue();
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用。
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//        }
//        System.out.println("回调参数：" + params.toString());
//        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
//        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
//        boolean flag = false;
//        try {
//            flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.ali_public_key, AlipayConfig.charset, AlipayConfig.SIGN_RSA2);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        if (!flag) {
//            LogUtils.error("回调结果：fail");
//            return "fail";
//        }
//        LogUtils.debug("回调结果：" + (flag ? "success" : "fail"));
//        AliCheckOrderReqParam orderReqDto = new AliCheckOrderReqParam(params);
//        if (orderReqDto.isSuccess()) {
//            Integer count = orderRecordService.findCount(orderReqDto.getInnerParam().getObjectIndex(), orderReqDto.getTrade_no());
//            if (count == null || count == 0) { //没有成功的记录，发送奖励
//                //TODO 发送奖励
//                //获取服务器id
//                Integer serverId = orderReqDto.getInnerParam().getServerId();
//                ServerModel serverModel = serverMapper.selectByPrimaryKey(serverId);
//                if (serverModel == null) {
//                    LogUtils.error("服务器找不到 id为:" + serverId);
//                    return "fail";
//                } else {
//                    RechargeParam rechargeParam = orderReqDto.getInnerParam();
//                    String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_ALI.name());
//                    boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), orderReqDto.getPassback_params(),
//                                                                        rechargeParam.getOutTradeNo(), orderReqDto.getTrade_no(), orderReqDto.getFee(), payType, payType);
//                    if(result)
//                    {
//                        orderRecordService.updateOrder(orderReqDto.getOrderRecordModel(payType), true);
//                        LogUtils.warn("支付宝冲值成功 -> " + rechargeParam.getOutTradeNo());
//                        return "success";
//                    }
//                    else
//                    {
//                        LogUtils.debug("主服务器冲值回调返回错误!");
//                        return "fail";
//                    }
//
////                    String checkString = orderReqDto.getInnerParam().getServerId() + ConstantFactory.RECHARGE_KEY +
////                            TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
////                    RechargeCallBackParam param = new RechargeCallBackParam();
////                    param.setObjectIndex(orderReqDto.getInnerParam().getObjectIndex());
////                    param.setRechargeParam(orderReqDto.getPassback_params());
////                    param.setOutTradeNo(orderReqDto.getInnerParam().getOutTradeNo());
////                    param.setTcd(orderReqDto.getTrade_no());
////                    param.setFee(orderReqDto.getFee());
////                    String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_ALI.name());
////                    param.setChannel(payType);
////                    param.setPayType(payType);
////                    param.setPassword(MD5Utils.encodeUppercase(checkString));
////
////                    JSONObject result = HttpJsonUtils.httpPost(serverModel.getMainServerRequestUrl() + HttpFactory.ORDER_CHECK, param.toJSONObject());
////                    if (result != null) {
////                        String resultCode = result.getString("code");
////                        if (Integer.parseInt(resultCode) == 0) {//成功
////                            orderRecordService.updateOrder(orderReqDto.getOrderRecordModel(payType), true);
////                            LogUtils.debug("充值成功");
////                            //充值成功调用talkingData
////                            return "success";
////                        } else {
////                            LogUtils.error("主服务器返回充值错误：" + result.getString("message"));
////                            return "fail";
////                        }
////                    } else {
////                        LogUtils.error("主服务器返回充值错误返回为空");
////                        return "fail";
////                    }
//                }
//
//            } else {
//                LogUtils.error("该用户已经发放过奖励");
//                return "success";
//            }
//        } else {
//            LogUtils.error("支付状态判断：fail");
//            return "fail";
//        }
//    }
//
//    @ResponseBody
//    @RequestMapping(value = HttpFactory.PAY_NOTIFY_TENPAY)
//    public void tenpayNotify(HttpServletRequest request, HttpServletResponse response)
//    {
//        try {
//            ServletInputStream inputStream = request.getInputStream();
//            int BUFFER_SIZE = 4096;
//            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//            byte[] data = new byte[BUFFER_SIZE];
//            int count = -1;
//            while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
//                outStream.write(data, 0, count);
//            }
//            byte[] outByte = outStream.toByteArray();
//            outStream.close();
//            String requestXmlContent = new String(outByte, "utf-8");
//
//            LogUtils.info("Tenpay notify request : " + requestXmlContent);
//
//            TenpayTradeNotifyInfo tradeNotifyInfo = TenpayTradeNotifyInfo.parseFromXML(requestXmlContent);
//
//            TenpayTradeReceiptInfo tradeReceiptInfo = TenpayTradeReceiptInfo.initFailInfo();
//            if(tradeNotifyInfo != null){
//                OrderRecordModel orderRecordModel = orderRecordService.findByOutTradeNo(tradeNotifyInfo.getOut_trade_no());
//                if(orderRecordModel != null)
//                {
//                    if (tradeNotifyInfo.verifySign()) {
//                        if(orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
//                            tradeReceiptInfo = TenpayTradeReceiptInfo.initSuccessInfo();
//                        else
//                        {
//                            if(tradeNotifyInfo.getResult_code().equals("SUCCESS"))
//                            {
//                                if(tradeNotifyInfo.getResult_code().equals("SUCCESS"))
//                                {
//                                    //自定义参数
//                                    RechargeParam rechargeParam = new RechargeParam(tradeNotifyInfo.getAttach());
//                                    ServerModel serverModel = serverMapper.selectByPrimaryKey(rechargeParam.getServerId());
//                                    if (serverModel == null)
//                                    {
//                                        LogUtils.error("服务器找不到 id为:" + rechargeParam.getServerId());
//                                    }
//                                    else
//                                    {
//                                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_WECHAT.name());
//                                        boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), tradeNotifyInfo.getAttach(),
//                                                                                            tradeNotifyInfo.getOut_trade_no(), tradeNotifyInfo.getOut_trade_no(), tradeNotifyInfo.getTotal_fee(), payType, payType);
//                                        if(result)
//                                        {
//                                            orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), payType, payType, rechargeParam.getRuleId(), tradeNotifyInfo.getOut_trade_no());
//                                            orderRecordService.updateOrder(orderRecordModel, false);
//                                            LogUtils.warn("微信冲值成功 -> " + tradeNotifyInfo.getOut_trade_no());
//                                            tradeReceiptInfo = TenpayTradeReceiptInfo.initSuccessInfo();
//                                        }
//                                        else
//                                        {
//                                            LogUtils.debug("主服务器冲值回调返回错误!");
//                                        }
//
////                                        String checkString = rechargeParam.getServerId() + ConstantFactory.RECHARGE_KEY + TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
////                                        RechargeCallBackParam param = new RechargeCallBackParam();
////                                        param.setObjectIndex(rechargeParam.getObjectIndex());
////                                        param.setRechargeParam(tradeNotifyInfo.getAttach());
////                                        param.setOutTradeNo(tradeNotifyInfo.getOut_trade_no());
////                                        param.setTcd(tradeNotifyInfo.getOut_trade_no());
////                                        param.setFee(tradeNotifyInfo.getTotal_fee());
////                                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_WECHAT.name());
////                                        param.setChannel(payType);
////                                        param.setPayType(payType);
////                                        param.setPassword(MD5Utils.encodeUppercase(checkString));
////                                        JSONObject result = HttpJsonUtils.httpPost(serverModel.getMainServerRequestUrl() + HttpFactory.ORDER_CHECK, param.toJSONObject());
////                                        if (result != null) {
////                                            String resultCode = result.getString("code");
////                                            if (Integer.parseInt(resultCode) == 0) {//成功
////                                                orderRecordModel.setStatus(E_RechargeStatus.PAY_SUCCESS.getCode());
////                                                //以下几个值没有存数据库，所以要在这里给值
////                                                orderRecordModel.setGameVersion(rechargeParam.getClientParam());
////                                                orderRecordModel.setVirtualCurrencyAmount(rechargeParam.getDiamonds());
////                                                orderRecordModel.setLevel(rechargeParam.getLv());
////                                                orderRecordModel.setChannel(payType);
////                                                orderRecordModel.setPaymentType(payType);
////                                                orderRecordModel.setPartner(rechargeParam.getRuleId());
////                                                orderRecordService.updateOrder(orderRecordModel, false);
////                                                LogUtils.debug("充值成功");
////                                                //充值成功调用talkingData
////                                                tradeReceiptInfo = TenpayTradeReceiptInfo.initSuccessInfo();
////                                            } else {
////                                                LogUtils.debug("主服务器返回充值错误：" + result.getString("message"));
////                                            }
////                                        } else {
////                                            LogUtils.debug("主服务器返回充值错误返回为空");
////                                        }
//                                    }
//                                }
//                                else
//                                {
//                                    LogUtils.error("支付失败 -> " + tradeNotifyInfo.getResult_code());
//                                    tradeReceiptInfo = TenpayTradeReceiptInfo.initSuccessInfo();
//                                }
//                            }
//                            else
//                            {
//                                LogUtils.error("Tenpay notify Error -> " + tradeNotifyInfo.getReturn_code());
//                            }
//                        }
//                    } else {
//                        LogUtils.error("Tenpay notify invalid signature, tenpay signature verification failed -> request : " + requestXmlContent);
//                    }
//
//                    String responseXml = tradeReceiptInfo.createRequestXML();
//                    LogUtils.info("tenpay notify " + tradeNotifyInfo.getOut_trade_no() + " -> response :" + responseXml);
//                    PrintWriter out = response.getWriter();
//                    out.write(responseXml);
//                    out.flush();
//                    out.close();
//                }
//                else
//                {
//                    LogUtils.error("OrderRecordModel is null -> outTradeNo:" + tradeNotifyInfo.getOut_trade_no());
//                }
//            }
//        } catch (Exception e) {
//            LogUtils.errorException(e);
//        }
//    }
//
//
//    /**
//     * 苹果支付的回调
//     *
//     * @throws Exception 苹果内购支付
//     * @throws
//     * @Title: doIosRequest
//     * @Description:Ios客户端内购支付
//     */
//    @RequestMapping(value = HttpFactory.PAY_NOTIFY_APPLEPAY, method = RequestMethod.POST)
//    public BaseResponseDto appstoreNotify(@RequestBody AppStoreNotifyParam reqDto)
//    {
//        LogUtils.info("收到苹果冲值验证----------->" + JSONObject.toJSONString(reqDto));
//        ReturnMessage errorInfo = reqDto.check();
//        if(errorInfo != null)
//            return new ErrorResponseDto(errorInfo);
//
//        ServerModel serverModel = null;
//        try{
//            serverModel = serverMapper.selectByPrimaryKey(reqDto.getServerId());
//            if (serverModel == null) {
//                LogUtils.error("服务器找不到 id为:" + reqDto.getServerId());
//                return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//            }
//        }catch (Exception e){
//            LogUtils.error("参数错误 -> serverId:" + reqDto);
//            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//        }
//
//        LogUtils.info("notify/appstore outTradeNo：" + reqDto.getOutTradeNo());
//        //因为查询苹果比较慢，所以单独开启线程处理
//        final ServerModel finalServerModel = serverModel;
//        WorldManager.getInstance().startThread(() ->{
//
//            LogUtils.info("开始验证苹果冲值订单 -> " + reqDto.getOutTradeNo());
//            String errorNotifyUrl = finalServerModel.getMainServerRequestUrl() + HttpFactory.ORDER_ERROR_NOTIFY;
//            RechargeCallBackParam resParam = new RechargeCallBackParam();
//            resParam.setObjectIndex(reqDto.getPlayerIndex());
//            String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_APPSTORE.name());
//            resParam.setChannel(payType);
//            resParam.setPayType(payType);
//            String checkString = finalServerModel.getId() + ConstantFactory.RECHARGE_KEY + TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
//            resParam.setPassword(MD5Utils.encodeUppercase(checkString));
//            resParam.setOutTradeNo(reqDto.getOutTradeNo());
//            try{
//                String outTradeNo = reqDto.getOutTradeNo();
//                OrderRecordModel tradeNoOrder = orderRecordService.findByOutTradeNo(outTradeNo);
//                OrderRecordModel transactionOrder = null;
//                if (tradeNoOrder != null && !Utils.isNullOrEmpty(tradeNoOrder.getTcd()) && tradeNoOrder.getTcd().equals(reqDto.getTransactionId()))
//                {
//                    LogUtils.error("数据库已经存了苹果订单号，但跟验证的参数不一样 -> 数据库的:" + tradeNoOrder.getTcd() + "  验证的:" + reqDto.getTransactionId());
//                    resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
//                    HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
//                }
//                else if(tradeNoOrder != null && tradeNoOrder.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
//                {
//                    LogUtils.info("已经支付成功 -> " + outTradeNo);
//                    resParam.setErrorMsg(ReturnMessage.REPEAT_REQUEST.getMsg());
//                    HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
//                }
//                else
//                {
//                    boolean canVerify = false;
//                    if(tradeNoOrder == null)
//                    {
//                        transactionOrder = orderRecordService.findByTcd(reqDto.getTransactionId());
//                        if(transactionOrder != null && transactionOrder.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
//                        {
//                            LogUtils.info("已经支付成功 -> " + reqDto.getTransactionId());
//                            resParam.setErrorMsg(ReturnMessage.REPEAT_REQUEST.getMsg());
//                            HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
//                        }
//                        else
//                        {
//                            //继续验证
//                            canVerify = true;
//                        }
//                    }
//                    else
//                    {
//                        //继续验证
//                        canVerify = true;
//                    }
//
//                    if(canVerify)
//                    {
//                        String verifyResult = ApplePayUtils.buyAppVerify(reqDto.getPayload(), false);            //1.先线上测试    发送平台验证
//                        if (verifyResult == null) {                                            // 苹果服务器没有返回验证结果
//                            LogUtils.error("正式环境无此订单信息!");
//                        } else {                                                                // 苹果验证有返回结果
//                            LogUtils.info("线上 -> " + reqDto.getOutTradeNo());
//                            JSONObject job = JSONObject.parseObject(verifyResult);
//                            String states = job.getString("status");
//
//                            if ("21007".equals(states)) {                                            //是沙盒环境，应沙盒测试，否则执行下面
//                                verifyResult = ApplePayUtils.buyAppVerify(reqDto.getPayload(), true);            //2.再沙盒测试  发送平台验证
//                                LogUtils.info("沙盒环境");
//                                job = JSONObject.parseObject(verifyResult);
//                                states = job.getString("status");
//                            }
//
//                            LogUtils.info("苹果平台返回值：job" + job);
//                            if (states.equals("0"))
//                            { // 前端所提供的收据是有效的    验证成功
//                                String r_receipt = job.getString("receipt");
//                                JSONObject returnJson = JSONObject.parseObject(r_receipt);
//                                JSONArray jsonArray = returnJson.getJSONArray("in_app");
//                                boolean isIn = false;
//                                String transactionId = reqDto.getTransactionId();
//                                String productId = "";//根据这个productId去确定真实金额
//                                for (int i = 0; i < jsonArray.size(); i++) {
//                                    if (reqDto.getTransactionId().equals(jsonArray.getJSONObject(i).getString("transaction_id"))) {
//                                        isIn = true;
//                                        productId = jsonArray.getJSONObject(i).getString("product_id");
//                                        break;
//                                    }
//                                }
//
//                                //如果单号一致  则保存到数据库
//                                if (isIn)
//                                {
//                                    LogUtils.info("苹果验证成功,现在开始本地验证是否这个订单已经处理过");
//                                    OrderRecordModel orderRecordModel = null;
//                                    if(tradeNoOrder != null)
//                                    {
//                                        orderRecordModel = tradeNoOrder;
//                                    }
//                                    else if(transactionOrder != null)
//                                    {
//                                        orderRecordModel = transactionOrder;
//                                    }
//
//                                    if (orderRecordModel != null && orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
//                                    {
//                                        LogUtils.info("订单 -> tcd:" + transactionId + " 已经验证过");
//                                        resParam.setErrorMsg(ReturnMessage.REPEAT_REQUEST.getMsg());
//                                        HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
//                                    }
//                                    else
//                                    {
//                                        int rechargeId = 0;
//                                        if(orderRecordModel == null)
//                                        {
//                                            //根据玩家流水号和服务器去查找
//                                            orderRecordModel = orderRecordService.findNoPayOrder(reqDto.getPlayerIndex(), finalServerModel.getId());
//                                        }
//
//                                        rechargeId = orderRecordModel == null ? 0 : orderRecordModel.getRechargeId();
//
//                                        if(rechargeId == 0)
//                                        {
//                                            LogUtils.error("获取rechargeId错误 -> playerIndex:" + reqDto.getPlayerIndex() + ", serverId:" + finalServerModel.getId());
//                                            resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
//                                            HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
//                                        }
//                                        else
//                                        {
//                                            JSONObject diamondResult = HttpJsonUtils.httpPost(finalServerModel.getMainServerRequestUrl() + HttpFactory.MANAGER_GET_RECHARGE_MONEY + "?rechargeId=" + rechargeId);
//                                            if(diamondResult == null)
//                                            {
//                                                LogUtils.error("从主服获取钻石数量错误 -> rechargeId:" + rechargeId);
//                                                resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
//                                                HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
//                                            }
//                                            else
//                                            {
//                                                int diamond = diamondResult.getJSONObject("data").getInteger("diamond");
//                                                int rmb = diamondResult.getJSONObject("data").getInteger("rmb") * 100;//转为分
//
//                                                String rechargeParam = PayUtils.createRechargeParam(reqDto.getPlayerIndex(), rechargeId, reqDto.getServerId(), reqDto.getPlayerLv(), diamond, reqDto.getServerRuleId(), null, null, outTradeNo);
//                                                resParam.setRechargeParam(rechargeParam);
//                                                resParam.setTcd(transactionId);//苹果的交易订单号
//                                                resParam.setFee(rmb);//保存为分
//
//                                                boolean result = PayUtils.checkOrderFromMainServer(finalServerModel.getMainServerRequestUrl(), resParam);
//                                                if(result)
//                                                {
//                                                    orderRecordModel.paySuccess(reqDto.getGameVersion(), diamond, reqDto.getPlayerLv(), payType, payType, reqDto.getServerRuleId(), transactionId);
//                                                    orderRecordService.updateOrder(orderRecordModel, false);
//                                                    LogUtils.warn("APPSTORE冲值成功 -> " + orderRecordModel.getOutTradeNo());
//                                                }
//                                                else
//                                                {
//                                                    LogUtils.debug("主服务器冲值回调返回错误!");
//                                                    //主服未通知成功,在玩家下一次登录时来认证服获取一下未通知成功的订单
//                                                    orderRecordModel.setStatus(E_RechargeStatus.VERIFY.getCode());
//                                                    orderRecordModel.setTcd(transactionId);
//                                                    orderRecordModel.setSsid(transactionId);
//                                                    orderRecordModel.setChannel(payType);
//                                                    orderRecordModel.setPaymentType(payType);
//                                                    orderRecordService.updateOrder(orderRecordModel, false);
//                                                }
//
////                                                String rechargeParam = PayUtils.createRechargeParam(reqDto.getPlayerIndex(), rechargeId, reqDto.getServerId(), reqDto.getPlayerLv(), diamond, reqDto.getServerRuleId(), null, null, outTradeNo);
////                                                resParam.setRechargeParam(rechargeParam);
////                                                resParam.setTcd(transactionId);//苹果的交易订单号
////                                                resParam.setFee(rmb);//保存为分
////
////                                                JSONObject result = HttpJsonUtils.httpPost(finalServerModel.getMainServerRequestUrl() + HttpFactory.ORDER_CHECK, resParam.toJSONObject());
////                                                if (result != null)
////                                                {
////                                                    String resultCode = result.getString("code");
////                                                    if (Integer.parseInt(resultCode) == 0)
////                                                    {//成功
////                                                        orderRecordModel.setStatus(E_RechargeStatus.PAY_SUCCESS.getCode());
////                                                        orderRecordModel.setLevel(reqDto.getPlayerLv());
////                                                        orderRecordModel.setTcd(transactionId);
////                                                        orderRecordModel.setSsid(transactionId);
////                                                        orderRecordModel.setVirtualCurrencyAmount(diamond);
////                                                        orderRecordModel.setChannel(payType);
////                                                        orderRecordModel.setPaymentType(payType);
////                                                        orderRecordModel.setPartner(reqDto.getServerRuleId());
////                                                        //以下几个值没有存数据库，所以要在这里给值
////                                                        orderRecordModel.setGameVersion(reqDto.getGameVersion());
////                                                        orderRecordService.updateOrder(orderRecordModel, false);
////                                                        LogUtils.info("充值成功 -> " + reqDto.getOutTradeNo());
////                                                    } else {
////                                                        LogUtils.error("主服务器返回充值错误：" + result.getString("message"));
////                                                        //主服未通知成功,在玩家下一次登录时来认证服获取一下未通知成功的订单
////                                                        orderRecordModel.setStatus(E_RechargeStatus.VERIFY.getCode());
////                                                        orderRecordModel.setTcd(transactionId);
////                                                        orderRecordModel.setSsid(transactionId);
////                                                        orderRecordModel.setChannel(payType);
////                                                        orderRecordModel.setPaymentType(payType);
////                                                        orderRecordService.updateOrder(orderRecordModel, false);
////                                                    }
////                                                } else {
////                                                    LogUtils.error("主服务器返回充值错误返回为空");
////
////                                                    //主服未通知成功,在玩家下一次登录时来认证服获取一下未通知成功的订单
////                                                    orderRecordModel.setStatus(E_RechargeStatus.VERIFY.getCode());
////                                                    orderRecordModel.setTcd(transactionId);
////                                                    orderRecordModel.setSsid(transactionId);
////                                                    orderRecordModel.setChannel(payType);
////                                                    orderRecordModel.setPaymentType(payType);
////                                                    orderRecordService.updateOrder(orderRecordModel, false);
////                                                }
//                                            }
//                                        }
//                                    }
//                                } else {
//                                    LogUtils.error("验证苹果冲值订单号错误 -> 苹果返回订单号:" + transactionId + "  验证订单的号:" + reqDto.getTransactionId());
//                                }
//                            } else {
//                                LogUtils.error("苹果冲值验证失败 -> " + states);
//                            }
//                        }
//                    }
//                    else
//                    {
//                        LogUtils.error("不能开始验证");
//                    }
//                }
//            }catch (Exception e){
//                LogUtils.errorException(e);
//                resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
//                HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
//            }
//        });
//
//        return new BaseResponseDto(ReturnMessage.SUCCESS);
//    }
//
//    @ResponseBody
//    @RequestMapping(value = HttpFactory.PAY_NOTIFY_PINGPING, method = RequestMethod.POST)
//    public String PPCheckOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        PPCheckOrderReqParam orderReqDto = new PPCheckOrderReqParam();
//        orderReqDto.init(request);
//        LogUtils.info("回调参数：" + orderReqDto.toString());
//        String fail = "fail";
//        String success = "success";
//        String sandBoxState = request.getParameter("X-Order-Sandbox");//沙盒状态
//        if (sandBoxState.equals("1")) {
//            //TODO 沙盒状态- -
//        }
//        if (orderReqDto.isResultOk()) {
//            if (orderReqDto.isSuccess()) {
//                RechargeParam rechargeParam = new RechargeParam(orderReqDto.getExtraInfo());
//                //查询订单
//                OrderRecordModel orderRecordModel = orderRecordService.findByOutTradeNo(orderReqDto.getBillNo());
//                if (orderRecordModel != null) {
//                    LogUtils.error("服务器找不到 id为:" + orderReqDto.getServerId());
//                    return fail;
//                } else {
//                    ServerModel serverModel = serverMapper.selectByPrimaryKey(Integer.valueOf(orderReqDto.getServerId()));
//                    if(serverModel == null)
//                    {
//                        LogUtils.error("服务器找不到 -> " + orderReqDto.getServerId());
//                        return fail;
//                    }
//                    else
//                    {
//                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_APPSTORE.name());
//                        String channel = PayUtils.getEnumType(SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_APPLE_PINGPING.name());
//                        int totalFee = Integer.parseInt(orderReqDto.getServerId().replace(".00", "")) * 100;//转为分
//                        boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), orderReqDto.getExtraInfo(),
//                                orderReqDto.getBillNo(), orderReqDto.getOrderId(), totalFee, payType, channel);
//                        if(result)
//                        {
//                            orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), channel, payType, rechargeParam.getRuleId(), orderReqDto.getOrderId());
//                            orderRecordService.updateOrder(orderRecordModel, false);
//                            LogUtils.info("平平充值成功 -> " + orderRecordModel.getOutTradeNo());
//                            return success;
//                        }
//                        else
//                        {
//                            LogUtils.debug("主服务器冲值回调返回错误!");
//                            return fail;
//                        }
//
////
////                        String checkString = orderReqDto.getServerId() + ConstantFactory.RECHARGE_KEY +
////                                TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
////                        Integer totalFee = Integer.parseInt(orderReqDto.getServerId().replace(".00", "")) * 100;//转为分
////                        RechargeCallBackParam param = new RechargeCallBackParam();
////                        param.setObjectIndex(rechargeParam.getObjectIndex());
////                        param.setRechargeParam(orderReqDto.getExtraInfo());
////                        param.setOutTradeNo(orderReqDto.getBillNo());
////                        param.setTcd(orderReqDto.getOrderId());
////                        param.setFee(totalFee);
////                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_APPSTORE.name());
////                        String channel = PayUtils.getEnumType(SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_APPLE_PINGPING.name());
////                        param.setChannel(channel);
////                        param.setPayType(payType);
////                        param.setPassword(MD5Utils.encodeUppercase(checkString));
////                        LogUtils.info("参数  -> " + JSONObject.toJSONString(param));
////                        LogUtils.info("通知主服务器 -> " + orderReqDto.getServerId());
////                        JSONObject result = HttpJsonUtils.httpPost(serverModel.getMainServerRequestUrl() + HttpFactory.ORDER_CHECK, param.toJSONObject());
////                        if (result != null) {
////                            String resultCode = result.getString("code");
////                            if (Integer.parseInt(resultCode) == 0) {
////                                orderRecordModel.setStatus(E_RechargeStatus.PAY_SUCCESS.getCode());
////                                //以下几个值没有存数据库，所以要在这里给值
////                                orderRecordModel.setGameVersion(rechargeParam.getClientParam());
////                                orderRecordModel.setVirtualCurrencyAmount(rechargeParam.getDiamonds());
////                                orderRecordModel.setGameVersion(orderRecordModel.getGameVersion());
////                                orderRecordModel.setLevel(rechargeParam.getLv());
////                                orderRecordModel.setChannel(channel);
////                                orderRecordModel.setPaymentType(payType);
////                                orderRecordModel.setPartner(rechargeParam.getRuleId());
////                                orderRecordService.updateOrder(orderRecordModel, false);
////                                LogUtils.info("充值成功 -> ");
////                                return success;
////                            } else {
////                                LogUtils.error("主服务器返回充值错误：" + result.getString("message"));
////                                return fail;
////                            }
////                        } else {
////                            LogUtils.error("主服务器返回充值错误返回为空");
////                            return fail;
////                        }
//                    }
//                }
//            } else {
//                return fail;
//            }
//        } else {
//            return fail;
//        }
//
//    }
//
//
//    /**
//     * 抢玩的回调
//     *
//     * @param request
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = HttpFactory.PAY_NOTIFY_QIANGWAN)
//    public String qwNotify(HttpServletRequest request)
//    {
//        String game_id = request.getParameter("game_id");
//        String platformOrderNo = request.getParameter("out_trade_no");
//        String price = request.getParameter("price");
//        String extend = request.getParameter("extend");
//        String sign = request.getParameter("sign");
//
//        String SUCCESS = "1";
//        String FAIL = "0";
//        if(PayUtils.isNullOrEmpty(game_id, platformOrderNo, price, extend, sign))
//        {
//            LogUtils.error("QIANG_WAN Notify Error -> game_id:" + game_id + ",platformOrder:" + platformOrderNo + ",price:" + price + ",extend:" + extend + ",sign:" + sign);
//            return FAIL;
//        }
//
//        String str = game_id + platformOrderNo + price + extend + PlatformFactory.QW_CHECK_PAY_KEY;
//        LogUtils.info("待加密的串 -> " + str);
//        String checkSign = MD5Utils.encode(str);
//        if(!sign.equals(checkSign))
//        {
//            LogUtils.error("QIANG_WAN sign Error -> sign:" + sign + "  checkSign:" + checkSign);
//            return FAIL;
//        }
//
//        try{
//            Integer totalFee = Integer.parseInt(price.replace(".00", "")) * 100;//转为分
//
//            RechargeParam rechargeParam = new RechargeParam(extend);
//
//            String outTradeNo = rechargeParam.getOutTradeNo();
//            OrderRecordModel orderRecordModel = orderRecordService.findByOutTradeNo(outTradeNo);
//            if(orderRecordModel == null)
//            {
//                LogUtils.error("QIANG_WAN 订单不存在->" + outTradeNo);
//                return FAIL;
//            }
//
//            if(orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
//            {
//                LogUtils.error("QIANG_WAN 订单已经成功，重复请求");
//                return FAIL;
//            }
//
//            ServerModel serverModel = serverMapper.selectByPrimaryKey(rechargeParam.getServerId());
//            if (serverModel == null)
//            {
//                LogUtils.error("服务器找不到 id为:" + rechargeParam.getServerId());
//                return FAIL;
//            }
//            else
//            {
//                String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_APPSTORE.name());
//                String channel = PayUtils.getEnumType(SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_APPLE_QIANGWAN.name());
//                boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), extend, outTradeNo, platformOrderNo, totalFee, payType, channel);
//                if(result)
//                {
//                    orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), channel, payType, rechargeParam.getRuleId(), platformOrderNo);
//                    orderRecordService.updateOrder(orderRecordModel, false);
//                    LogUtils.debug("充值成功");
//                    return SUCCESS;
//                }
//                else
//                {
//                    LogUtils.error("主服务器返回充值错误");
//                    return FAIL;
//                }
////                String checkString = rechargeParam.getServerId() + ConstantFactory.RECHARGE_KEY + TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
////                RechargeCallBackParam param = new RechargeCallBackParam();
////                param.setObjectIndex(rechargeParam.getObjectIndex());
////                param.setRechargeParam(extend);
////                param.setOutTradeNo(outTradeNo);
////                param.setTcd(platformOrderNo);
////                param.setFee(totalFee);
////
////                param.setChannel(channel);
////                param.setPayType(payType);
////                param.setPassword(MD5Utils.encodeUppercase(checkString));
////
////                JSONObject result = HttpJsonUtils.httpPost(serverModel.getMainServerRequestUrl() + HttpFactory.ORDER_CHECK, param.toJSONObject());
////                if (result != null) {
////                    String resultCode = result.getString("code");
////                    if (Integer.parseInt(resultCode) == 0) {//成功
////                        orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), channel, payType, rechargeParam.getRuleId(), platformOrderNo);
////                        orderRecordService.updateOrder(orderRecordModel, false);
////                        LogUtils.debug("充值成功");
////                    } else {
////                        LogUtils.error("主服务器返回充值错误：" + result.getString("message"));
////                    }
////                } else {
////                    LogUtils.error("主服务器返回充值错误返回为空");
////                }
//            }
////
////            return SUCCESS;
//        }catch (Exception e)
//        {
//            LogUtils.errorException(e);
//            return FAIL;
//        }
//    }
//
//    @ResponseBody
//    @RequestMapping(value = HttpFactory.PAY_NOTIFY_QUICKSDK)
//    public String quicksdkNotify(HttpServletRequest request)
//    {
//        String data = request.getParameter("nt_data");
//        String sign = request.getParameter("sign");
//        String md5Sign = request.getParameter("md5Sign");
//        if(Utils.isNullOrEmpty(data) || Utils.isNullOrEmpty(sign) || Utils.isNullOrEmpty(md5Sign))
//        {
//            return "PARAM_ERROR";
//        }
//
//
//        return "SUCCESS";
//    }
//
//
//}
